require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const schedule = require('node-schedule');
const path = require('path');
const WeChatCrawler = require('./crawler');
const PublicAccount = require('./models/publicAccount');
const Article = require('./models/article');

// 连接MongoDB数据库
mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('MongoDB连接成功'))
  .catch(err => console.error('MongoDB连接失败:', err));

// 创建Express应用
const app = express();

// 配置模板引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// 配置中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由配置
app.get('/', async (req, res) => {
  try {
    const accounts = await PublicAccount.find().sort('-createdAt');
    const articles = await Article.find().sort('-publishDate').limit(10);
    res.render('index', { accounts, articles });
  } catch (error) {
    res.status(500).send('服务器错误');
  }
});

// 添加公众号
app.post('/accounts', async (req, res) => {
  try {
    const { name, biz, description } = req.body;
    await PublicAccount.create({ name, biz, description });
    res.redirect('/');
  } catch (error) {
    res.status(500).send('添加公众号失败');
  }
});

// 删除公众号
app.post('/accounts/:id/delete', async (req, res) => {
  try {
    await PublicAccount.findByIdAndDelete(req.params.id);
    res.redirect('/');
  } catch (error) {
    res.status(500).send('删除公众号失败');
  }
});

// 手动触发抓取
app.post('/crawl', async (req, res) => {
  try {
    const crawler = new WeChatCrawler();
    await crawler.init();
    await crawler.login();
    await crawler.crawlAllAccounts();
    await crawler.close();
    res.redirect('/');
  } catch (error) {
    res.status(500).send('抓取失败');
  }
});

// 配置定时任务
schedule.scheduleJob(process.env.CRON_SCHEDULE, async () => {
  console.log('开始定时抓取任务...');
  const crawler = new WeChatCrawler();
  try {
    await crawler.init();
    await crawler.login();
    await crawler.crawlAllAccounts();
  } catch (error) {
    console.error('定时抓取任务失败:', error);
  } finally {
    await crawler.close();
  }
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});